package com.example.demo.netty.single;

import com.example.demo.netty.CustomChannelInBoundHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;

// 假设有一个单线程的Reactor，负责监听、接收连接、读写操作
class SingleThreadReactor {
    public static void main (String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup(1); // 创建一个只有1个线程的EventLoopGroup
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(group)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel (SocketChannel ch) throws Exception {
                            // 设置ChannelPipeline中的处理器
//                            ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(new StringDecoder());

                            ch.pipeline().addLast(new CustomChannelInBoundHandler());
                        }
                    });

            // 绑定端口并启动服务器
            ChannelFuture f = b.bind(8080).sync();
            // 等待服务器关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅关闭EventLoopGroup
            group.shutdownGracefully();
        }
    }
}